import recursionRouter from '@/utils/permission.js'
import { DynamicRoutes } from '@/router/index.js'
import router from '@/router/index.js'
let res = {
  userName: '丫丫',
  roles: [
    {
      path: '/',
      name: 'home',
    },
    {
      path: '/learn',
      name: 'learn',
      children: [
        {
          path: 'promisetest',
          name: 'promiseTest',
        },
        {
          path: 'checkbox',
          name: 'checkBox',
        },
      ],
    },
  ],
}
const state = {
  get UserToken() {
    return localStorage.getItem('token')
  },
  set UserToken(value) {
    localStorage.setItem('token', value)
  },
  get USER_NAME() {
    return localStorage.getItem('userName')
  },
  set USER_NAME(value) {
    localStorage.setItem('userName', value)
  },
  roles: [],
}
const mutations = {
  LOGIN_IN(state, token) {
    state.UserToken = token
  },
  LOGIN_OUT(state) {
    state.UserToken = ''
  },
  SET_USERNAME(state, val) {
    state.USER_NAME = val
  },
  REMOVE_USERNAME(state) {
    state.USER_NAME = ''
  },
  ADD_ROLES(state, val) {
    state.roles = val
  },
}

const actions = {
  logIn(context) {
    return new Promise(function(resolve, reject) {
      let res = {}
      setTimeout(function() {
        res = { userName: '丫丫' }
        // 存入token
        context.commit('LOGIN_IN', 'logined')
        context.commit('SET_USERNAME', res.userName)
        resolve(res)
      }, 0)
    })
  },
  FETCH_USERINFO(context) {
    return new Promise(function(resolve, reject) {
      setTimeout(function() {
        let routes = recursionRouter(res.roles, DynamicRoutes)
        router.addRoutes(routes)
        context.commit('SET_USERNAME', res.userName)
        context.commit('ADD_ROLES', routes)
        resolve(res)
      }, 0)
    })
  },
}

export default {
  state,
  mutations,
  actions,
}
